package com.example.propertymanagement.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * SecurityConfig：配置 BCryptPasswordEncoder 用于密码加密
 */
@Configuration
public class SecurityConfig {

    /**
     * 创建并返回一个 BCryptPasswordEncoder Bean，用于加密和验证密码
     * @return BCryptPasswordEncoder 加密器
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();  // 返回一个 BCryptPasswordEncoder 实例
    }

    /**
     * 安全过滤链配置（放行 Swagger 相关路径）
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(auth -> auth  // 使用 authorizeRequests() 而不是 authorizeHttpRequests()
                        .antMatchers(  // 使用 antMatchers() 直接传入字符串路径
                                "/swagger-ui.html",
                                "/swagger-ui/**",
                                "/v3/api-docs/**",
                                "/swagger-resources/**",
                                "/webjars/**"
                        ).permitAll()
                        .anyRequest().authenticated()
                )
                .csrf().disable();  // 旧版写法，直接调用 .disable()

        return http.build();
    }
}